<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"tallgy.gitee.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>
<meta name="description" content="内在深入响应式原理​        在前面我们可以知道，当我们修改了data里面的数据时，视图也会进行更新。这样使得状态的管理非常的直接。 如何追踪变化​        Vue会将data里的数据使用 Object.defineProperty ，将这些 property 全部转为 getter&#x2F;setter。因为 Object.defineProperty 是一个无法shim的特性。所以这也是V">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue-使用-内在">
<meta property="og:url" content="http://tallgy.gitee.io/2021/10/29/Vue/Vue2-%E6%95%99%E7%A8%8B/Vue2-%E6%95%99%E7%A8%8B-%E5%86%85%E5%9C%A8/index.html">
<meta property="og:site_name" content="tallgy&#39;s blog">
<meta property="og:description" content="内在深入响应式原理​        在前面我们可以知道，当我们修改了data里面的数据时，视图也会进行更新。这样使得状态的管理非常的直接。 如何追踪变化​        Vue会将data里的数据使用 Object.defineProperty ，将这些 property 全部转为 getter&#x2F;setter。因为 Object.defineProperty 是一个无法shim的特性。所以这也是V">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://tallgy.gitee.io/.io//image-20211214103613477.png">
<meta property="article:published_time" content="2021-10-29T15:16:15.000Z">
<meta property="article:modified_time" content="2023-06-25T08:57:29.323Z">
<meta property="article:author" content="tallgy">
<meta property="article:tag" content="Vue">
<meta property="article:tag" content="文档">
<meta property="article:tag" content="Vue2">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://tallgy.gitee.io/.io//image-20211214103613477.png">


<link rel="canonical" href="http://tallgy.gitee.io/2021/10/29/Vue/Vue2-%E6%95%99%E7%A8%8B/Vue2-%E6%95%99%E7%A8%8B-%E5%86%85%E5%9C%A8/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://tallgy.gitee.io/2021/10/29/Vue/Vue2-%E6%95%99%E7%A8%8B/Vue2-%E6%95%99%E7%A8%8B-%E5%86%85%E5%9C%A8/","path":"2021/10/29/Vue/Vue2-教程/Vue2-教程-内在/","title":"Vue-使用-内在"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Vue-使用-内在 | tallgy's blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">tallgy's blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%86%85%E5%9C%A8"><span class="nav-number">1.</span> <span class="nav-text">内在</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B7%B1%E5%85%A5%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86"><span class="nav-number">1.1.</span> <span class="nav-text">深入响应式原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E8%BF%BD%E8%B8%AA%E5%8F%98%E5%8C%96"><span class="nav-number">1.1.1.</span> <span class="nav-text">如何追踪变化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A3%80%E6%B5%8B%E5%8F%98%E5%8C%96%E7%9A%84%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="nav-number">1.1.2.</span> <span class="nav-text">检测变化的注意事项</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AF%B9%E4%BA%8E%E5%AF%B9%E8%B1%A1"><span class="nav-number">1.1.2.1.</span> <span class="nav-text">对于对象</span></a></li></ol></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">tallgy</p>
  <div class="site-description" itemprop="description">只是一个知识的搬运工</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">107</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">74</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://tallgy.gitee.io/2021/10/29/Vue/Vue2-%E6%95%99%E7%A8%8B/Vue2-%E6%95%99%E7%A8%8B-%E5%86%85%E5%9C%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="tallgy">
      <meta itemprop="description" content="只是一个知识的搬运工">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="tallgy's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Vue-使用-内在
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-10-29 23:16:15" itemprop="dateCreated datePublished" datetime="2021-10-29T23:16:15+08:00">2021-10-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2023-06-25 16:57:29" itemprop="dateModified" datetime="2023-06-25T16:57:29+08:00">2023-06-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Vue/Vue2/" itemprop="url" rel="index"><span itemprop="name">Vue2</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="内在"><a href="#内在" class="headerlink" title="内在"></a>内在</h1><h2 id="深入响应式原理"><a href="#深入响应式原理" class="headerlink" title="深入响应式原理"></a>深入响应式原理</h2><p>​        在前面我们可以知道，当我们修改了data里面的数据时，视图也会进行更新。这样使得状态的管理非常的直接。</p>
<h3 id="如何追踪变化"><a href="#如何追踪变化" class="headerlink" title="如何追踪变化"></a>如何追踪变化</h3><p>​        Vue会将data里的数据使用 Object.defineProperty ，将这些 property 全部转为 getter/setter。因为 Object.defineProperty 是一个无法shim的特性。所以这也是Vue不支持IE8以及更低的版本的原因。</p>
<p>​        getter/setter 在 property 被访问和修改的时候通知变更。</p>
<p>​        每一个组件的实例都对应一个 watcher 实例，他会在组件渲染的过程中把 接触过的数据 property 记录为依赖。然后当 setter 触发时，通知 watcher，从而重新渲染。</p>
<img src="/.io//image-20211214103613477.png" alt="image-20211214103613477" style="zoom:67%;">

<p>​    data会被变更为 getter和setter，然后在视图使用到数据时，便会调用getter，然后添加入了一个dep依赖(这个是使用一个数组进行维护)。当数据发生改变时，会通过notify通知给watcher，然后watcher将会把dep数组的数据重新渲染。</p>
<h3 id="检测变化的注意事项"><a href="#检测变化的注意事项" class="headerlink" title="检测变化的注意事项"></a>检测变化的注意事项</h3><p>​        由于JavaScript的限制，Vue不能检测数组和对象的变化。</p>
<h4 id="对于对象"><a href="#对于对象" class="headerlink" title="对于对象"></a>对于对象</h4><p>​        对于对象来说，无法检测 property 的添加或移除。所以property必须在data对象上存在才能让vue将它转换为响应式的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">var vm = new Vue(&#123;</span><br><span class="line">  data:&#123;</span><br><span class="line">    a:1</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">// `vm.a` 是响应式的</span><br><span class="line"></span><br><span class="line">vm.b = 2</span><br><span class="line">// `vm.b` 是非响应式的</span><br></pre></td></tr></table></figure>

<p>​        对于已经创建的实例，Vue不允许动态添加根级别的响应式 property。但是可以使用 Vue.set(object, propertyName, value) 方法向嵌套对象添加响应式 property。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Vue.set(vm.someObject, &#x27;b&#x27;, 2)</span><br></pre></td></tr></table></figure>

<p>​    当然可以使用 vm.$set 实例方法，这也是全局 Vue.set 方法的别名</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">this.$set(this.someObject, &#x27;b&#x27;, 2)</span><br><span class="line"></span><br><span class="line">this.$set(this.a, &#x27;b&#x27;, 123)</span><br></pre></td></tr></table></figure>

<p>​        有时你可能需要为已有的对象赋值多个新的property，比如使用 Object.assign() 或者 _.extend()。但是，这样添加并不会触发事件。此时需要将新的对象返回覆盖才能触发。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// Object.assign(this.someObject, &#123;a:1, b:2&#125;)</span><br><span class="line">this.someObject = Object.assign(&#123;&#125;, this.someObject, &#123;a:1, b:2&#125;)</span><br></pre></td></tr></table></figure>

<p>​    通过这个方法，我们可以知道几个知识点：</p>
<ul>
<li><p>Object.assign 是将第二个参数及其以后的赋值给第一个，对于重复的，会被覆盖，后面的会覆盖前面的。</p>
</li>
<li><p>第二点，这里为什么会被更新呢，其实并不是将someObject的内部的对象进行了 getter和setter 操作，而是因为someObject被修改了地址，所以我们也可以知道，这个 Object.defineProperty 是将这个值所指向的位置的监听。</p>
<ul>
<li><p>因为对象是堆的存放，而 Object.defineProperty 监听的是栈的值，所以对于对象内部的修改不会被监听到。而将新的对象赋值给了这个对象，此时对象的普通赋值是一个浅拷贝，只拷贝栈值，所以栈被修改了，导致了内部的数据全部都会进行一个监听。</p>
</li>
<li><p>而如果使用 this.$set(this.someObject, ‘o’, value)的话，仅仅只是将这个o的指向进行了监听，而不会监听其他的错误操作。比如：</p>
<ul>
<li><pre><code>this.a.c = 123
// 此时这个d加入了监听，但是对于c来说，并不会加入监听。因为c是一个错误添加方式。虽然不会进行监听，但是 &#123;&#123; a &#125;&#125;这样的输出还是会将c进行显示的，因为输出的是a，a.c虽然没有加入监听，但是仍然是属于a的。
this.$set(this.a, &#39;d&#39;, 1)

但是使用 Object.assign
这样，对于c来说也会进行监听，因为此时是将原来的this.a进行了栈的修改，对象已经不是一个对象了，此时Vue就会进行一个递归的操作，将新的对象全部进行一个监听。
this.a = Object.assign(&#123;&#125;, this.a, &#123;a:1, b:2&#125;)
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#### 对于数组</span><br><span class="line"></span><br><span class="line">​		Vue对于数组的监听是将数组的方法进行了一个覆盖，在使用原来的方法的同时，也在里面加入了监听的方法，所以对于直接修改数组下标的将不会进行修改。</span><br><span class="line"></span><br><span class="line">​		Vue不能检测以下数组的变动：</span><br><span class="line"></span><br><span class="line">* 通过索引直接进行修改 arr[index] = newValue</span><br><span class="line">* 修改数组的长度 arr.length = newLength</span><br><span class="line"></span><br><span class="line">对于使用 下标进行修改的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
这里可以使用，可以考虑JavaScript数组也是对象的想法
this.$set(this.arr, index, newValue)
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"></span><br></pre></td></tr></table></figure>
this.splice(index, 1, newValue)
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">对于修改数组长度的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
this.arr.splice(newLength)
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">### 声明响应式 property</span><br><span class="line"></span><br><span class="line">​		我们可以发现，前面的添加数据的方式，要不就是数组方法的添加，要不就是在对象里面进行添加，而并没有直接新添加一个对象的形式。由此可以知道：Vue是不运行动态添加根级响应式property的。对于根级响应式必须要提前进行申明。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">### 异步更新队列</span><br><span class="line"></span><br><span class="line">​		Vue在更新数据是异步进行更新的。对于数据的变化，Vue将开启一个队列。缓冲同一个事件循环的所有数据变更。如果watcher被多次触发，将只会被推入到队列中一次。这样可以不必要的操作和DOM的计算。然后在下一个事件循环中，在刷新队列执行的实际操作。 Promise.then() 、 MutationObserver 和 setImmediate，如果执行环境不支持，则会采用 setTimeout(fn, 0) 进行代替。</span><br><span class="line"></span><br><span class="line">​		当然这样虽然有了好处，节省了性能，但是同时，如果我们要进行dom操作时将会出现问题，因为异步的原因，dom获取的值是在上一次所剩下的。此时便有了一个方法，this.$nextTick(callback)，将方法写入this.$nextTick，然后这个方法将会在下次事件循环，dom操作之后进行获取。</span><br><span class="line"></span><br></pre></td></tr></table></figure>
methods: &#123;
updateMessage: function () &#123;
  this.message = &#39;已更新&#39;
  console.log(this.$el.textContent) // =&gt; &#39;未更新&#39;
  this.$nextTick(function () &#123;
      console.log(this.$el.textContent) // =&gt; &#39;已更新&#39;
  &#125;)
&#125;
&#125;
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">​	并且 this.$nextTick 返回的是一个 promise 对象，所以你可以使用新的 async/await 语法完成相同的事情</span><br><span class="line"></span><br></pre></td></tr></table></figure>
methods: &#123;
updateMessage: async function () &#123;
this.message = &#39;已更新&#39;
console.log(this.$el.textContent) // =&gt; &#39;未更新&#39;
await this.$nextTick()
console.log(this.$el.textContent) // =&gt; &#39;已更新&#39;
&#125;
&#125;
</code></pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"># Vue</a>
              <a href="/tags/%E6%96%87%E6%A1%A3/" rel="tag"># 文档</a>
              <a href="/tags/Vue2/" rel="tag"># Vue2</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/10/29/Vue/Vue2-%E6%95%99%E7%A8%8B/Vue2-%E6%95%99%E7%A8%8B-%E8%A7%84%E6%A8%A1%E5%8C%96/" rel="prev" title="Vue-使用-规模化">
                  <i class="fa fa-chevron-left"></i> Vue-使用-规模化
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/10/30/HTML/HTML-%E6%A0%87%E7%AD%BE%E7%9A%84title/" rel="next" title="HTML-标签的title">
                  HTML-标签的title <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">tallgy</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
